package com.zhiwang.xiaoqu.ui.withdraw


import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import com.bumptech.glide.Glide
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.di.component.DaggerUserComponent
import com.zhiwang.xiaoqu.di.module.AutoDisposeModule
import com.zhiwang.xiaoqu.mvp.model.response.WithDrawItem
import com.zhiwang.xiaoqu.mvp.presenter.SmsPresenter
import com.zhiwang.xiaoqu.mvp.presenter.UserPresenter
import com.zhiwang.xiaoqu.ui.BaseFragment
import com.zhiwang.xiaoqu.widget.Toasty
import kotlinx.android.synthetic.main.fragment_ali_withdraw.*
import kotlinx.android.synthetic.main.recyclerview.*
import me.drakeet.multitype.MultiTypeAdapter
import javax.inject.Inject

/**
 * A simple [Fragment] subclass.
 */
class AliWithdrawFragment : BaseFragment(), View.OnClickListener {

    @Inject
    lateinit var userPresenter: UserPresenter

    @Inject
    lateinit var smsPresenter: SmsPresenter
    var fragmentInteractListener: WithDrawFragmentInteractListener? = null


    var isBind = false

    var token: String = System.currentTimeMillis().toString()

    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is WithDrawFragmentInteractListener)
            fragmentInteractListener = context
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_ali_withdraw, container, false)
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        load()
    }

    private fun load() {
        if (isBind) {
            ali_bind_layout.visibility = View.VISIBLE
            ali_nobind_layout.visibility = View.GONE
            loadGraphCode()
            userPresenter.getAliWithDrawList(::onWithDrawListLoad, ::onBindError)
        } else {
            ali_bind_layout.visibility = View.GONE
            ali_nobind_layout.visibility = View.VISIBLE
            ali_bind_btn.setOnClickListener(this)
            iv_graphcode.setOnClickListener {
                loadGraphCode()
            }
            loadGraphCode()
            colddown_timer.setOnClickListener(this)
        }

        tv_withdraw_btn.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.colddown_timer -> { //短信倒计时
                if (checkSmsEnabled()) {
                    if (colddown_timer.isCounting) return
                    val phone = et_ali_phone_account.text.toString().trim()
                    val graphCode = et_graphcode.text.toString().trim()
                    smsPresenter.getBindSmsCode(phone, graphCode, token, ::onSmsSend, ::onError)
                }
//                    colddown_timer.start()

            }

            R.id.ali_bind_btn -> { // 开始绑定
                if (checkBindEnabled()) {
                    val phone = et_phone.text.toString().trim()
                    val phoneAccount = et_ali_phone_account.text.toString().trim()
                    val graphCode = et_graphcode.text.toString()
                    val smsCode = et_sms_code.text.toString()
                    userPresenter.bindAliAccount(
                        phone,
                        phoneAccount,
                        graphCode,
                        smsCode,
                        ::onAccountBound,
                        ::onBindError
                    )
                }
            }

            R.id.tv_withdraw_btn -> {
                val num = withDrawList[withDrawViewBinder.curr].num
                if (fragmentInteractListener?.checkBalanceWithDrawEnabled(num = num.toInt()) != false)
                    userPresenter.withdrawAli(num, onSuccess = ::onWithDrawSuccess, onError = ::onError)
                else {
                    Toasty.message(getString(R.string.balance_not_enough))
                }
            }
        }
    }

    fun onWithDrawSuccess(msg: String) = Toasty.message(msg)

    fun onSmsSend() {
        colddown_timer.start()
    }

    private fun onAccountBound() {
        //todo 数据库写入 已绑定标识
        Toasty.message("支付宝绑定成功")
        isBind = true
        load()
    }

    fun onBindError(t: Throwable) {
        loadGraphCode()
        onError(t)
    }

    private fun checkBindEnabled(): Boolean {
        val phone = et_phone.text.toString()
        val phoneAccount = et_ali_phone_account.text.toString()
        val smsCode = et_sms_code.text.toString()

        if (phone.isEmpty()) {
            Toasty.message("手机号为空")
            return false
        } else if (phoneAccount.isEmpty()) {
            Toasty.message("账户名为空")
            return false
        } else if (smsCode.isEmpty()) {
            Toasty.message("短信验证码为空")
            return false
        }
        return true
    }

    private fun checkSmsEnabled(): Boolean {

        val phoneAccount = et_ali_phone_account.text.toString()
        if (phoneAccount.isEmpty() || phoneAccount.length != 11) {
            Toasty.message("请输入正确的手机号")
            return false
        }
        return true
    }

    private fun loadGraphCode() {
        token = System.currentTimeMillis().toString()
        Glide.with(this)
            .load(BuildConfig.BASE_URL + "api/app_vcode?tu_token=$token&vcode_type=app_bind")
            .into(iv_graphcode)
    }


    lateinit var withDrawList: List<WithDrawItem>

    private val withDrawViewBinder = WithDrawItemViewBinder()

    private fun onWithDrawListLoad(list: List<WithDrawItem>) {
        withDrawList = list
        recyclerView.layoutManager = GridLayoutManager(context, 3)
        val typeAdapter = MultiTypeAdapter()
        typeAdapter.items = list
        val payLoad = listOf(Object())
        typeAdapter.register(WithDrawItem::class.java, withDrawViewBinder)
        recyclerView.adapter = typeAdapter
        typeAdapter.notifyItemChanged(0, payLoad)
    }


}
